//
//  FFJMessageManager.m
//  Common
//
//  Created by ale tan on 2017/9/18.
//  Copyright © 2017年 IT.Bear. All rights reserved.
//

#import "FFJMessageManager.h"
//#import "FFLoginViewModel.h"
#import "FFCache.h"

#import "FFTools.h"
#import <AdSupport/ASIdentifierManager.h>
#import <UserNotifications/UserNotifications.h>

#import "JMUIChattingViewController.h"

//#import "FFConfiguration.h"
//#import "FFContent_VC.h"

#import "Common.h"
//#import "FFUserInfo.h"
#import "FFCache.h"

//#import "FFRefundOrderModel.h"

//#import "FFLoginManager.h"

//#import "NSString+Encryption.h"
//#import "FFPayResult_VC.h"



static FFJMessageManager *jmessageManger;

@interface FFJMessageManager ()<JMessageDelegate,UIAlertViewDelegate>

@property (nonatomic ,strong)JMSGConversation *conversation;

@end

@implementation FFJMessageManager

+ (FFJMessageManager *)sharedInstance {
    static dispatch_once_t oncetoken;
    dispatch_once(&oncetoken,^{
        if (!jmessageManger) {
            jmessageManger = [[self alloc] init];
            jmessageManger.unBandAccount = [FFCache queryCache:UNBAND_ACOUNT];
            jmessageManger.unBandPassword = [FFCache queryCache:UNBAND_PASSWORD];
        }
    });
    return jmessageManger;
}

#pragma mark -RequestAccount-
- (void)requestForJmessageAcount:(GetJMessageAcount)getJMessageAcount{
//    FFLoginViewModel *viewModel = [[FFLoginViewModel alloc]init];
//    [viewModel requestForJMessageAcountWithCallBack:^(id responseDic, BOOL result) {
//        if (result) {
//            self.unBandAccount = responseDic[@"data"][@"jmessage_name"];
//            self.unBandPassword = responseDic[@"data"][@"password"];
//
//            [FFCache addCache:UNBAND_ACOUNT obj:self.unBandAccount];
//            [FFCache addCache:UNBAND_PASSWORD obj:self.unBandPassword];
//
//            if (getJMessageAcount) {
//                getJMessageAcount(YES);
//            }
//        }
//        else{
//            [self requestForJmessageAcount:getJMessageAcount];
//        }
//    }];
}

#pragma mark
- (void)jMessageRegisterWithOptions:(NSDictionary *)launchOptions{
    
    //Required
    
    [JMessage setupJMessage:launchOptions appKey:JPUSHKEY channel:nil apsForProduction:NO category:nil messageRoaming:YES];
}

#pragma mark - 向服务器上报Device Token
- (void)registerDeviceToken:(NSData *)deviceToken{
    [JMessage registerDeviceToken:deviceToken];
}

#pragma mark -注册-
- (void)registerWithCompletionHandler:(JMSGCompletionHandler JMSG_NULLABLE)handler{
//    FFUserInfo *userinfo = [FFCache queryCache:USER_INFO];
//    [JMSGUser registerWithUsername:userinfo.phone password:userinfo.easemobPwd completionHandler:^(id resultObject, NSError *error) {
//        if (!error) {
//            //注册成功
//        } else {
//            //注册失败
//        }
//
//        if (handler) {
//            handler(resultObject,error);
//        }
//    }];
}

#pragma mark -登录-
- (void)loginWithCompletionHandler:(JMSGCompletionHandler JMSG_NULLABLE)handler{
//    FFUserInfo *userinfo = [FFCache queryCache:USER_INFO];
    NSString *acount = @"account";//userinfo.jmessage_name;
    NSString *password = @"password";//userinfo.jmessage_name;
//    if (!acount || !acount.length) {
//        if (self.unBandAccount && self.unBandAccount.length) {
//            acount = self.unBandAccount;
//            password = self.unBandPassword;
//        }
//        else{
//            [self requestForJmessageAcount:^(BOOL success) {
//                if (success) {
//                    [self loginWithCompletionHandler:^(id resultObject, NSError *error) {
//
//                    }];
//                }
//            }];
//            return;
//        }
//    }
    
    [JMSGUser loginWithUsername:acount password:password completionHandler:^(id resultObject, NSError *error) {
        if (!error) {
            //登录成功
            NSLog(@"极光登录成功 %@",acount);
            [JMessage addDelegate:self withConversation:nil];
            
            [JMSGConversation createSingleConversationWithUsername:JMessageServiceAcount completionHandler:^(id resultObject, NSError *error) {
                if (!error) {
                    _conversation = (JMSGConversation *)resultObject;
                    [_conversation refreshTargetInfoFromServer:^(id resultObject, NSError *error) {
                        
                    }];
                }
            }];
            
        } else {
            //登录失败
            NSLog(@"极光登录失败");
        }
        
        if (handler) {
            handler(resultObject,error);
        }
    }];
}

#pragma mark -JMessageDelegate-极光事件回调，如被挤掉
//- (void)onReceiveNotificationEvent:(JMSGNotificationEvent *)event{
//    switch (event.eventType) {
//        case kJMSGEventNotificationCurrentUserInfoChange:
//            NSLog(@"Current user info change Event ");
//            break;
//        case kJMSGEventNotificationReceiveFriendInvitation:
//            NSLog(@"Receive Friend Invitation Event ");
//            break;
//        case kJMSGEventNotificationAcceptedFriendInvitation:
//            NSLog(@"Accepted Friend Invitation Event ");
//            break;
//        case kJMSGEventNotificationDeclinedFriendInvitation:
//            NSLog(@"Declined Friend Invitation Event ");
//            break;
//        case kJMSGEventNotificationDeletedFriend:
//            NSLog(@"Deleted Friend Event ");
//            break;
//        case kJMSGEventNotificationReceiveServerFriendUpdate:
//            NSLog(@"Receive Server Friend Update Event ");
//            break;
//        case kJMSGEventNotificationLoginKicked:
//        {
//            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"" message:event.eventDescription delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
//            [alertView show];
//            NSLog(@"Login Kicked Event ");
//        }
//            break;
//        case kJMSGEventNotificationServerAlterPassword:
//            NSLog(@"Server Alter Password Event ");
//            break;
//        case kJMSGEventNotificationUserLoginStatusUnexpected:
//            NSLog(@"User login status unexpected Event ");
//            break;
//        default:
//            NSLog(@"Other Notification Event ");
//            break;
//    }
//}

//收到在线消息
- (void)onReceiveMessage:(JMSGMessage *)message error:(NSError *)error{
    NSLog(@"在线消息");
    [_conversation refreshTargetInfoFromServer:^(id resultObject, NSError *error) {
        
    }];
    if (!error) {
        UINavigationController *nav = [self getNavigation];
        if (![nav.topViewController isKindOfClass:[JMUIConversationViewController class]]) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"tabbarBadge" object:@"show"];
        }
    }
}

//收到离线消息
- (void)onSyncOfflineMessageConversation:(JMSGConversation *)conversation offlineMessages:(NSArray<__kindof JMSGMessage *> *)offlineMessages{
    NSLog(@"离线消息");
    [_conversation refreshTargetInfoFromServer:^(id resultObject, NSError *error) {
        
    }];
    UINavigationController *nav = [self getNavigation];
    if (![nav.topViewController isKindOfClass:[JMUIConversationViewController class]]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"tabbarBadge" object:@"show"];
    }
}

//收到漫游消息
- (void)onSyncRoamingMessageConversation:(JMSGConversation *)conversation{
    NSLog(@"漫游消息");
    [_conversation refreshTargetInfoFromServer:^(id resultObject, NSError *error) {
        
    }];
    UINavigationController *nav = [self getNavigation];
    if (![nav.topViewController isKindOfClass:[JMUIConversationViewController class]]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"tabbarBadge" object:@"show"];
    }
}

#pragma mark -UIAlertView-
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    [self logout:nil];
//    [[FFLoginManager sharedInstance] doLoginOutInVC:nil];
}

#pragma mark -退出登录-
- (void)logout:(JMSGCompletionHandler)handler{
    [JMSGUser logout:^(id resultObject, NSError *error) {
        if (!error) {
            //退出登录成功
        } else {
            //退出登录失败
        }
        
        if (handler) {
            handler(resultObject,error);
        }
    }];
}

#pragma mark -发送消息-
- (void)sendMessage:(id)message Type:(CustomMessageType)type{
    JMUIConversationViewController *conversationVC = [JMUIConversationViewController new];
    
    BOOL hasChatView = NO;
    UINavigationController *navi = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    NSArray *viewControllers = navi.childViewControllers;
    for (UIViewController *viewController in viewControllers) {
        if ([viewController isKindOfClass:[JMUIConversationViewController class]]) {
            conversationVC = (JMUIConversationViewController *)viewController;
            hasChatView = YES;
            break;
        }
    }
    
    conversationVC.hidesBottomBarWhenPushed = YES;
    
    //添加个人信息
    NSMutableDictionary *userDic = [NSMutableDictionary dictionary];
//    if ([[FFLoginManager sharedInstance] isLogin]) {
//        FFUserInfo *userinfo = [FFCache queryCache:USER_INFO];
//
//        //用户名称
//        if (userinfo.nick) {
//            [userDic setObject:userinfo.nick forKey:@"nickname"];
//        }
//        else{
//            [userDic setObject:[NSString stringWithFormat:@"手机用户%@",userinfo.phone] forKey:@"nickname"];
//        }
//
//        //头像
//        if (userinfo.face_icon) {
//            [userDic setObject:userinfo.face_icon forKey:@"avatar"];
//        }
//    }
//    else{
        [userDic setObject:[NSString stringWithFormat:@"游客%@",self.unBandAccount] forKey:@"nickname"];
//    }
    
    NSMutableDictionary *content = [NSMutableDictionary dictionary];
    switch (type) {
        //商品
        case CustomMessageTypeProduct:
        {
            FBProductModel *model = (FBProductModel *)message;
            [content setValuesForKeysWithDictionary:[self productToDictionary:model]];
        }
            break;
         
        //订单
        case CustomMessageTypeOrder:
        {
            FBOrderModel *order = (FBOrderModel *)message;
            
            if (order.orderNo) {
                [content setObject:order.orderNo forKey:@"orderNo"];
            }

            //h5链接
            NSString *orderAddress = [NSString stringWithFormat:@"html/productdetails.html?product_id=%@",order.orderNo];
            NSString *orderUrl = MAIN_SERVER(orderAddress);
            [content setObject:orderUrl forKey:@"link_url"];
            
            if (order.products.count) {
                NSMutableArray *products = [NSMutableArray array];
                for (FBProductModel *product in order.products) {
                    [products addObject:[self productToDictionary:product]];
                }
                [content setObject:products forKey:@"products"];
            }
        }
            break;
            
        //退款单
//        case CustomMessageTypeRefund:
//        {
//            FFRefundOrderModel *refundOrder = (FFRefundOrderModel *)message;
//
//            if (refundOrder.order_no) {
//                [content setObject:refundOrder.order_no forKey:@"order_no"];
//            }
//
//            if (refundOrder.order_id) {
//                [content setObject:refundOrder.order_id forKey:@"order_id"];
//            }
//
//            if (refundOrder.refund_id) {
//                [content setObject:refundOrder.refund_id forKey:@"refund_id"];
//            }
//
//            //h5链接
//            NSString *orderAddress = [NSString stringWithFormat:@"html/productdetails.html?product_id=%@",refundOrder.product_id];
//            NSString *orderUrl = MAIN_SERVER(orderAddress);
//            [content setObject:orderUrl forKey:@"link_url"];
//
//            if (refundOrder.products.count) {
//                NSMutableArray *products = [NSMutableArray array];
//                for (FFProductsModel *product in refundOrder.products) {
//                    [products addObject:[self productToDictionary:product]];
//                }
//                [content setObject:products forKey:@"products"];
//            }
//        }
//            break;
         
        //询图单
//        case CustomMessageTypeConsult:
//        {
//            FFImageConsultModel *model = (FFImageConsultModel *)message;
//            
//            if (model.isCreated) {
//                [content setObject:@"1" forKey:@"isCreated"];
//            }
//            
//            if (model.order_no) {
//                [content setObject:model.order_no forKey:@"order_no"];
//            }
//            if (model.consult_id) {
//                [content setObject:model.consult_id forKey:@"consult_id"];
//            }
//            if (model.consult_status) {
//                [content setObject:model.consult_status forKey:@"consult_status"];
//            }
//            if (model.consult_status_text) {
//                [content setObject:model.consult_status_text forKey:@"consult_status_text"];
//            }
//            
//            if (model.consult_products.count) {
//                NSMutableArray *products = [NSMutableArray array];
//                for (FFProductsModel *product in model.consult_products) {
//                    [products addObject:[self productToDictionary:product]];
//                }
//                [content setObject:products forKey:@"consult_products"];
//            }
//            if (model.match_products.count) {
//                NSMutableArray *products = [NSMutableArray array];
//                for (FFProductsModel *product in model.match_products) {
//                    [products addObject:[self productToDictionary:product]];
//                }
//                [content setObject:products forKey:@"match_products"];
//            }
//        }
//            break;
            
        default:
        {
            content = message;
        }
            break;
    }
    
    NSString *contentStr = [content jsonStringEncoded];
    if (type == CustomMessageTypeText || type == CustomMessageTypeImage) {
        contentStr = message;
    }
    
    if (!_conversation) {
        [JMSGConversation createSingleConversationWithUsername:JMessageServiceAcount completionHandler:^(id resultObject, NSError *error) {
            if (!error) {
                _conversation = (JMSGConversation *)resultObject;
            }
            
            if (message) {
                JMSGCustomContent *customContent = [[JMSGCustomContent alloc]initWithCustomDictionary:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%lu",(unsigned long)type],@"type",contentStr,@"content",[userDic jsonStringEncoded],@"user", nil]];
                JMSGMessage *customMessage = [JMSGMessage createSingleMessageWithContent:customContent username:JMessageServiceAcount];
                conversationVC.forSendMessage = customMessage;
            }
            
            conversationVC.conversation = _conversation;
            if (!hasChatView) {
                [[self getNavigation] pushViewController:conversationVC animated:YES];
            }
        }];
    }
    else{
        if (message) {
            JMSGCustomContent *customContent = [[JMSGCustomContent alloc]initWithCustomDictionary:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%lu",(unsigned long)type],@"type",contentStr,@"content",[userDic jsonStringEncoded],@"user", nil]];
            JMSGMessage *customMessage = [JMSGMessage createSingleMessageWithContent:customContent username:JMessageServiceAcount];
            conversationVC.forSendMessage = customMessage;
        }
        
        conversationVC.conversation = _conversation;
        if (!hasChatView) {
            [[self getNavigation] pushViewController:conversationVC animated:YES];
        }
    }
}

- (UINavigationController *)getNavigation
{
    return (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
}

#pragma mark -Tools-
- (NSDictionary *)productToDictionary:(FBProductModel *)model{
    NSMutableDictionary *content = [NSMutableDictionary dictionary];
    
    //produc_id
    if (model.productId) {
        [content setObject:model.productId forKey:@"productId"];
        
        //h5链接
        NSString *orderAddress = [NSString stringWithFormat:@"html/productdetails.html?product_id=%@",model.productId];
        NSString *orderUrl = MAIN_SERVER(orderAddress);
        [content setObject:orderUrl forKey:@"link_url"];
    }
    
    //produc_sku_id
    if (model.productSkuId) {
        [content setObject:model.productSkuId forKey:@"productSkuId"];
    }
    
    //choise_id
//    if (model.choice_id) {
//        [content setObject:model.choice_id forKey:@"choice_id"];
//    }
    
    //图片
    if (model.cover) {
        [content setObject:model.cover forKey:@"productCover"];
    }
    else if(model.productCover){
        [content setObject:model.productCover forKey:@"productCover"];
    }
//    else if (model.image_urls.count) {
//        [content setObject:model.image_urls forKey:@"image_urls"];
//    }
    
    //品牌
    if (model.designerName) {
        [content setObject:model.designerName forKey:@"designerName"];
    }
    
    //产品名称
    if (model.productName) {
        [content setObject:model.productName forKey:@"productName"];
    }
    
    //尺码
    if (model.size) {
        [content setObject:model.size forKey:@"size"];
    }
    
    //价格
    if (model.showPrice) {
        if (model.currencyLogo) {
            [content setObject:model.currencyLogo forKey:@"currencyLogo"];
        }
        
        [content setObject:model.showPrice forKey:@"showPrice"];
    }
    
    //数量
    if (model.productQty) {
        [content setObject:model.productQty forKey:@"productQty"];
    }
    
    return content;
}

/*!
 *
 * @param message 未读消息数量。
 *
 */
- (NSInteger)getUnreadMessage{
    if (!_conversation) {
        return 0;
    }
    else{
        return [_conversation.unreadCount integerValue];
    }
}

/*!
 *
 * @param message 最后一条消息。
 *
 */
- (JMSGMessage *)lastMessage{
    if (!_conversation) {
        return nil;
    }
    else{
        return _conversation.latestMessage;
    }
}

@end
